package com.example;
import java.util.*;

class Solution {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> mappings = new HashMap();
        List result = new ArrayList();
        // parse the domain names and count
        for (String domain :cpdomains) {
            String[] contents = domain.split("\\s+"); // seperate the counts and domain name by 'space'
            String[] segments = contents[1].split("\\."); // seperate the subdomain by '.'
            int cnt = Integer.valueOf(contents[0]); // get the counts and transfer it from string to integer type
            //System.out.println(cnt);
            //System.out.println(segments[0]);
            //System.out.println(segments[1]);
            String line = ""; 
            // construct the line with subdomains 
            // add the counts into the same subdomain string by hashmap 
            for (int i = segments.length-1;i >=0; i--) {
                line = segments[i] + (i< segments.length-1 ? ".":"") + line;
                //System.out.println(line);
                mappings.put(line, mappings.getOrDefault(line, 0) + cnt);
            }
        }
        // combine count
        for (String sub : mappings.keySet()) {
            result.add("" + mappings.get(sub)+ " "+ sub);
        }
        
        return result;
 }
}